﻿using System.Data;

namespace Aore.Utility.Dapper;

public static class DapperCommon
{
  /// <summary>
  /// ReplaceConnectionsParamPrefix(: -> @)
  /// </summary>
  private static readonly List<string> ReplaceConnectionsParamPrefix = new List<string>() { "SqlConnection", "MySqlConnection", "NpgsqlConnection", "SQLiteConnection" };

  /// <summary>
  /// SQL参数前缀替换，支持原生Camstar参数前缀（?）的写法；Orcale、SQLServer、MySQL、PostgreSQL、SQLite等数据参数前缀统一使用（:）
  /// </summary>
  /// <param name="dbConnection"></param>
  /// <param name="commonTxt"></param>
  /// <returns></returns>
  public static string ParameterReplace(IDbConnection? dbConnection, string commonTxt)
  {

    try
    {
      if (!string.IsNullOrEmpty(commonTxt))
      {
        if (commonTxt.Contains("?"))
        {
          commonTxt = commonTxt.Replace("?", ":");
        }
        else if (commonTxt.Contains("？"))
        {
          commonTxt = commonTxt.Replace("？", ":");
        }
        else if (commonTxt.Contains("#"))
        {
          commonTxt = commonTxt.Replace("#", ":");
        }
        else if (commonTxt.Contains("@"))
        {
          commonTxt = commonTxt.Replace("@", ":");
        }
      }
      else
      {
        return commonTxt;
      }

      if (dbConnection != null && ReplaceConnectionsParamPrefix.Contains(dbConnection.GetType().Name))
      {
        if (commonTxt.Contains(":"))
        {
          return commonTxt.Replace(":", "@");
        }

        if (commonTxt.Contains("："))
        {
          return commonTxt.Replace("：", "@");
        }

        return commonTxt;
      }
      else
      {
        return commonTxt;
      }
    }
    catch
    {
      return commonTxt;
    }
  }
}